package list;

public class ArrayList<E> extends AbstractList<E>{
	
	public static final int DEFAULT_CAPACITY = 16;	// 自定义
	
	
	private E[] elements;
	
	
	public ArrayList() {
		elements = (E[])new Object[DEFAULT_CAPACITY];
	}
	
	public ArrayList(int capacity) {
		capacity = capacity < DEFAULT_CAPACITY ? DEFAULT_CAPACITY : capacity;
		elements = (E[])new Object[capacity];
	}
	
	
	public void add(int index, E element) {
		checkIndexForAdd(index);
		ensureCapacity(size + 1);
		for (int i = size; i > index; i--) {
			elements[i] = elements[i - 1];
		}
		elements[index] = element;
		size++;
	}
	
	public E get(int index) {
		checkIndex(index);
		return elements[index];
	}
	
	public E set(int index, E element) {
		checkIndex(index);
		E oldElement = elements[index];
		elements[index] = element;
		return oldElement;
	}
	
	public E remove(int index) {
		checkIndex(index);
		E oldElement = elements[index];
		for (int i = index + 1; i < size; i++) {
			elements[i - 1] = elements[i];
		}
		elements[--size] = null;
		trim();
		return oldElement;
	}
	
	
	public int indexOf(E element) {
		if (element == null) {
			for (int i = 0; i < size; i++) {
				if (elements[i] == null) return i;
			}
		} else {
			for (int i = 0; i < size; i++) {
				if (element.equals(elements[i])) return i;
			}
		}
		return ELEMENT_NOT_FOUND;
	}
	
	public void clear() {
		for (int i = 0; i < size; i++) {
			elements[i] = null;
		}
		size = 0;
	}

	@Override
	public String toString() {
		if (size == 0) return "[]";
		StringBuilder sb = new StringBuilder(size * 2 + 50);
		sb.append("[");
		for (int i = 0; i < size; i++) {
			if (i != 0) {
				sb.append(", ");
			}
			sb.append(elements[i]);
		}
		sb.append("]");
		return sb.toString();
	}
	
	/**
	 * 动态数组扩容
	 * @param capacity
	 */
	private void ensureCapacity(int capacity) {
		int oldCapacity = elements.length;
		if (oldCapacity >= capacity) return;
		// 数组容量不足, 扩容
		int newCapacity = oldCapacity + (oldCapacity >> 1);
		E[] newElements = (E[])new Object[newCapacity];
		for (int i = 0; i < size; i++) {
			newElements[i] = elements[i];
		}
		elements = newElements;
		System.out.println(oldCapacity + "扩容为" + newCapacity);
	}
	
	/**
	 * 动态数组缩容
	 */
	private void trim() {
		int newCapacity = elements.length >> 1;
		if (size >= newCapacity || newCapacity < DEFAULT_CAPACITY) return;
		// 数组缩容
		E[] newElements = (E[])new Object[newCapacity];
		for (int i = 0; i < size; i++) {
			newElements[i] = elements[i];
		}
		elements = newElements;
	}
}
